<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<u-navbar bgColor="#FFFFFF" :placeholder="true">
			<view slot="left" class="navbar-left">
				<navigator url="/pageNew/ContractManage/index" class="back-button">
					<u-icon color="#333333" name="arrow-left" size="20"></u-icon>
					<view class="navbar-title">合同管理</view>
				</navigator>
			</view>
			<view slot="right" class="navbar-right">
				<view class="nav-item" @click="handleBatchOperation" v-if="selectedContracts.length > 0">
					<u-icon color="#333333" name="checkmark-circle" size="20"></u-icon>
				</view>
				<view class="nav-item" @click="scanContract">
					<u-icon color="#999999" name="scan" size="20"></u-icon>
				</view>
			</view>
		</u-navbar>

		<!-- 搜索栏 -->
		<view class="search-container">
			<view class="container">
				<view class="search-wrap">
					<input type="text" placeholder="请输入合同名称或公司名称" class="search-input" v-model="searchKeyword">
					<text class="search-btn" @click="handleSearch">搜索</text>
				</view>
			</view>
		</view>

		<!-- 标签栏 -->
		<view class="tab-container">
			<view class="container">
				<view class="tab-list">
					<view class="tab-item" :class="activeTab === 'signed' ? 'tab-active' : ''"
						@click="switchTab('signed')">已签约</view>
					<view class="tab-item" :class="activeTab === 'unsigned' ? 'tab-active' : ''"
						@click="switchTab('unsigned')">未签约</view>
					<view class="tab-item" :class="activeTab === 'expired' ? 'tab-active' : ''"
						@click="switchTab('expired')">到期</view>
				</view>
			</view>
		</view>

		<!-- 批量操作栏 -->
		<view class="batch-bar" v-if="selectedContracts.length > 0">
			<view class="batch-content">
				<view class="batch-select">
					<u-icon name="checkbox-mark" color="#4285F4" size="18"></u-icon>
					<text class="batch-count">已选择 {{ selectedContracts.length }} 项</text>
				</view>
				<view class="batch-actions">
					<view class="batch-btn" @click="handleBatchDownload" v-if="hasDownloadPermission">
						<u-icon name="download" color="#333333" size="18"></u-icon>
						<text>批量下载</text>
					</view>
					<view class="batch-btn" @click="handleBatchSign" v-if="hasSignPermission">
						<u-icon name="edit-pen" color="#28A745" size="18"></u-icon>
						<text>批量签署</text>
					</view>
					<view class="batch-btn" @click="clearSelection">
						<u-icon name="close" color="#FF0000" size="18"></u-icon>
						<text>取消</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 合同列表 -->
		<view class="content-container">
			<view class="contract-list" v-if="filteredContracts.length > 0">
				<view class="contract-card" v-for="(item, index) in filteredContracts" :key="item.id">
					<view class="card-header">
						<view class="checkbox-container" @click.stop="toggleSelection(item)">
							<u-icon :name="isSelected(item) ? 'checkbox-mark' : ''" color="#4285F4" size="20"
								class="checkbox-icon"></u-icon>
						</view>
						<view class="company-name">{{ item.companyName }}</view>
						<view class="contract-status" :class="[getStatusClass(item)]">
							<text>{{ getStatusText(item) }}</text>
						</view>
					</view>
					<view class="contract-info">
						<view class="info-row">
							<text class="info-label">申报类型：</text>
							<text class="info-value">{{ item.declareType }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">授权代理人：</text>
							<text class="info-value">{{ item.agent }}</text>
							<text class="info-label">签订日期：</text>
							<text
								:class="item.signDate === '未签署' ? 'info-value red' : 'info-value'">{{ item.signDate }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">开始日期：</text>
							<text class="info-value">{{ item.startDate }}</text>
							<text class="info-label">结束日期：</text>
							<text class="info-value">{{ item.endDate }}</text>
						</view>
					</view>
					<view class="action-buttons">
						<view class="action-btn preview" @click="handlePreview(item)">
							<u-icon name="eye" size="14" class="btn-icon"></u-icon>
							预览
						</view>
						<view class="action-btn download" @click="handleDownload(item)">
							<u-icon name="download" size="14" class="btn-icon"></u-icon>
							下载
						</view>
						<view v-if="item.signStatus === 0" class="action-btn sign" @click="handleSign(item)">
							<u-icon name="edit-pen" size="14" class="btn-icon"></u-icon>
							签署
						</view>
					</view>
				</view>
			</view>
			<!-- 修复：空状态图标替换为支持的 file-text -->
			<view class="no-data" v-else>
				<u-icon name="file-text" size="40" color="#CCCCCC"></u-icon>
				<text class="no-data-title">暂无合同记录</text>
				<text class="no-data-desc">点击右下角按钮添加新合同</text>
			</view>
		</view>

		<!-- 新增按钮 -->
		<view class="add-btn" @click="handleAdd">
			<u-icon name="plus" size="24" color="#FFFFFF"></u-icon>
		</view>

		<!-- 加载中提示 -->
		<u-loading-page v-if="loading" :loading-text="loadingText"></u-loading-page>

		<!-- 批量操作确认弹窗 -->
		<u-modal v-model="batchModalVisible" :show-cancel-button="true" :show-confirm-button="true"
			:title="batchModalTitle" @confirm="confirmBatchOperation" @cancel="cancelBatchOperation">
			<view class="batch-modal-content">
				<text>{{ batchModalContent }}</text>
				<view class="batch-count-info" v-if="batchModalCount > 0">
					<text>共 {{ batchModalCount }} 份合同</text>
				</view>
			</view>
		</u-modal>

		<!-- 操作结果提示 -->
		<u-toast ref="toast" :message="toastMessage" :type="toastType" :duration="2000"></u-toast>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				defaultStartDate: this.formatDate(new Date()), // 初始化默认日期为今天
				activeTab: 'unsigned', // 默认选中未签约标签
				searchKeyword: '',
				contracts: [], // 合同列表数据，从接口获取
				selectedContracts: [], // 选中的合同
				loading: false, // 加载状态
				loadingText: '处理中...', // 加载提示文本
				batchModalVisible: false, // 批量操作确认弹窗
				batchModalTitle: '', // 批量操作弹窗标题
				batchModalContent: '', // 批量操作弹窗内容
				batchModalCount: 0, // 批量操作数量
				batchOperationType: '', // 批量操作类型：download/sign
				toastMessage: '', // 提示消息
				toastType: 'success', // 提示类型：success/error/warning/info
				scannedContract: null, // 扫描识别的合同
				http: uni.$u.http, // 统一请求实例
				companyInfo: uni.getStorageSync('companyInfo') // 公司信息
			};
		},
		computed: {
			// 获取公司ID
			companyId() {
				return this.companyInfo.id || '';
			},

			filteredContracts() {
				let result = [...this.contracts]; // 先获取所有合同数据

				// 标签筛选：严格匹配后端signStatus定义（0=未签署，1=已签署，2=已到期）
				if (this.activeTab === 'signed') {
					// 已签约：signStatus=1（后端明确1是已签署）
					result = result.filter(item => item.signStatus === 1);
				} else if (this.activeTab === 'unsigned') {
					// 未签约：signStatus=0（后端明确0是未签署）
					result = result.filter(item => item.signStatus === 0);
				} else if (this.activeTab === 'expired') {
					// 已到期：signStatus=2（后端明确2是已到期，无需额外判断日期）
					result = result.filter(item => item.signStatus === 2);
				}

				// 搜索筛选
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					result = result.filter(item =>
						item.companyName.toLowerCase().includes(keyword) ||
						item.contractNo.toLowerCase().includes(keyword)
					);
				}
				return result;
			},
			// 是否有批量下载权限（至少有一个选中的合同）
			hasDownloadPermission() {
				return this.selectedContracts.length > 0;
			},
			// 是否有批量签署权限（选中的合同都是未签署状态）
			hasSignPermission() {
				return this.selectedContracts.length > 0 &&
					this.selectedContracts.every(item => item.signStatus === 0);
			}
		},
		onLoad() {
			// 页面初次加载时获取合同列表
			this.getContractList();
		},
		// 修复：新增 onShow 生命周期，每次页面显示时刷新数据（解决返回不刷新问题）
		onShow() {
			// 从添加页、详情页返回时，重新获取数据
			this.getContractList();
		},
		methods: {
			// 从接口获取合同列表（核心修复：数据解析路径+格式适配）
			async getContractList() {
				this.loading = true;
				this.loadingText = '加载中...';

				try {
					const res = await this.http.get('/VipVipcontract/list', {
						params: {
							companyId: this.companyId,
							pageSize: 100 // 获取较多数据，避免分页
						}
					});

					// 适配接口返回格式：code=200，数据在 res.data.data 中
					if (res && res.code === 200 && res.data.data) {
						// 格式化合同数据，适配前端显示
						this.contracts = res.data.data.map(item => {
							return {
								...item,
								// 日期处理：null时显示对应文本，非null直接使用后端格式（YYYY-MM-DD）
								signDate: item.signDate || '未签署',
								startDate: item.startDate || '--',
								endDate: item.endDate || '--'
							};
						});
					} else {
						this.showToast('获取合同列表失败', 'error');
					}
				} catch (error) {
					console.error('获取合同列表异常:', error);
					this.showToast('获取合同列表异常', 'error');
				} finally {
					this.loading = false;
				}
			},

			// 格式化日期为 'YYYY-MM-DD'（仅用于签署时生成日期）
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 切换标签
			switchTab(tab) {
				this.activeTab = tab;
				this.clearSelection(); // 切换标签时清除选择
			},

			// 处理搜索
			handleSearch() {
				// 搜索时重新获取数据
				this.getContractList();
				this.clearSelection(); // 搜索时清除选择
			},

			// 预览合同
			handlePreview(item) {
				uni.navigateTo({
					url: `/pages/contract/detail?id=${item.id}`
				});
			},

			// 下载合同
			handleDownload(item) {
				if (!item.contractFileUrl) {
					this.showToast('合同文件不存在', 'warning');
					return;
				}

				this.loading = true;
				this.loadingText = '正在下载...';

				// 调用下载接口
				uni.downloadFile({
					url: item.contractFileUrl,
					success: (res) => {
						this.loading = false;
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true,
								success: () => {
									this.showToast('下载成功', 'success');
								},
								fail: () => {
									this.showToast('打开文件失败', 'error');
								}
							});
						} else {
							this.showToast('下载失败', 'error');
						}
					},
					fail: () => {
						this.loading = false;
						this.showToast('下载失败', 'error');
					}
				});
			},

			// 签署合同
			async handleSign(item) {
				this.loading = true;
				this.loadingText = '正在签署...';

				try {
					// 调用签署接口
					const res = await this.http.post('/VipVipcontractSignature/insert', {
						contractId: item.id,
						companyId: this.companyId,
						signerName: item.agent, // 用授权代理人作为签署人
						signType: 0 // 签署类型（根据后端要求调整）
					});

					if (res && res.code === 200) {
						// 更新合同状态（与后端signStatus一致：1=已签署）
						const today = this.formatDate(new Date());
						const endDate = new Date();
						endDate.setFullYear(endDate.getFullYear() + 1);
						const endDateStr = this.formatDate(endDate);

						const index = this.contracts.findIndex(contract => contract.id === item.id);
						if (index !== -1) {
							this.contracts[index].signStatus = 1;
							this.contracts[index].signDate = today;
							this.contracts[index].startDate = today;
							this.contracts[index].endDate = endDateStr;
						}

						this.showToast('签署成功', 'success');
					} else {
						this.showToast(res.msg || '签署失败', 'error');
					}
				} catch (error) {
					console.error('签署合同异常:', error);
					this.showToast('签署合同异常', 'error');
				} finally {
					this.loading = false;
				}
			},

			// 新增合同
			handleAdd() {
				uni.navigateTo({
					url: '/pageNew/ContractManage/add'
				});
			},

			// 扫描合同
			scanContract() {
				// 调用 uni.scanCode 实现真实扫码功能
				uni.scanCode({
					success: (res) => {
						// 假设扫描结果是合同编号
						const contractNo = res.result;
						const contract = this.contracts.find(item => item.contractNo === contractNo);

						if (contract) {
							this.scannedContract = contract;
							this.showToast(`扫描成功，找到合同：${contract.companyName}`, 'success');

							// 跳转到合同详情页
							setTimeout(() => {
								this.handlePreview(contract);
							}, 1000);
						} else {
							this.showToast('未找到对应合同', 'error');
						}
					},
					fail: () => {
						this.showToast('扫描失败', 'error');
					}
				});
			},

			// 切换合同选择状态
			toggleSelection(item) {
				const index = this.selectedContracts.findIndex(contract => contract.id === item.id);
				if (index === -1) {
					// 选中合同
					this.selectedContracts.push(item);
				} else {
					// 取消选中
					this.selectedContracts.splice(index, 1);
				}
			},

			// 判断合同是否被选中
			isSelected(item) {
				return this.selectedContracts.some(contract => contract.id === item.id);
			},

			// 清除所有选择
			clearSelection() {
				this.selectedContracts = [];
			},

			// 处理批量操作
			handleBatchOperation() {
				// 批量操作逻辑（可根据需求扩展）
			},

			// 处理批量下载
			handleBatchDownload() {
				this.batchModalTitle = '批量下载确认';
				this.batchModalContent = '确定要下载选中的合同吗？';
				this.batchModalCount = this.selectedContracts.length;
				this.batchOperationType = 'download';
				this.batchModalVisible = true;
			},

			// 处理批量签署
			handleBatchSign() {
				this.batchModalTitle = '批量签署确认';
				this.batchModalContent = '确定要签署选中的合同吗？签署后将更新合同状态和日期。';
				this.batchModalCount = this.selectedContracts.length;
				this.batchOperationType = 'sign';
				this.batchModalVisible = true;
			},

			// 确认批量操作
			async confirmBatchOperation() {
				this.batchModalVisible = false;
				this.loading = true;

				if (this.batchOperationType === 'download') {
					this.loadingText = '正在批量下载...';

					// 批量下载逻辑
					try {
						// 获取选中合同的ID列表
						const contractIds = this.selectedContracts.map(item => item.id);

						const res = await this.http.post('/VipVipcontract/batchDownload', {
							ids: contractIds,
							companyId: this.companyId
						});

						if (res && res.code === 200 && res.data) {
							// 处理批量下载结果，通常是一个打包文件的URL
							uni.downloadFile({
								url: res.data,
								success: (downloadRes) => {
									if (downloadRes.statusCode === 200) {
										uni.openDocument({
											filePath: downloadRes.tempFilePath,
											showMenu: true
										});
									}
								}
							});
							this.showToast(`成功下载 ${this.batchModalCount} 份合同`, 'success');
						} else {
							this.showToast('批量下载失败', 'error');
						}
					} catch (error) {
						console.error('批量下载异常:', error);
						this.showToast('批量下载异常', 'error');
					} finally {
						this.loading = false;
						this.clearSelection();
					}
				} else if (this.batchOperationType === 'sign') {
					this.loadingText = '正在批量签署...';

					// 批量签署逻辑
					try {
						// 获取选中合同的ID列表
						const contractIds = this.selectedContracts.map(item => item.id);

						const res = await this.http.post('/VipVipcontractSignature/batchInsert', {
							contractIds: contractIds,
							companyId: this.companyId,
							signerType: 0 // 签署类型（根据后端要求调整）
						});

						if (res && res.code === 200) {
							const today = this.formatDate(new Date());
							const endDate = new Date();
							endDate.setFullYear(endDate.getFullYear() + 1);
							const endDateStr = this.formatDate(endDate);

							// 更新选中合同的状态（与后端一致：1=已签署）
							this.selectedContracts.forEach(selectedItem => {
								const index = this.contracts.findIndex(item => item.id === selectedItem.id);
								if (index !== -1) {
									this.contracts[index].signStatus = 1;
									this.contracts[index].signDate = today;
									this.contracts[index].startDate = today;
									this.contracts[index].endDate = endDateStr;
								}
							});

							this.showToast(`成功签署 ${this.batchModalCount} 份合同`, 'success');
						} else {
							this.showToast(res.msg || '批量签署失败', 'error');
						}
					} catch (error) {
						console.error('批量签署异常:', error);
						this.showToast('批量签署异常', 'error');
					} finally {
						this.loading = false;
						this.clearSelection();
					}
				}
			},

			// 取消批量操作
			cancelBatchOperation() {
				this.batchModalVisible = false;
			},

			// 获取合同状态文本（匹配后端signStatus：0=未签署，1=已签署，2=已到期）
			getStatusText(item) {
				switch (item.signStatus) {
					case 0:
						return '未签署';
					case 1:
						return '已签署';
					case 2:
						return '已到期';
					default:
						return '未知状态';
				}
			},

			// 获取合同状态样式（匹配后端signStatus）
			getStatusClass(item) {
				switch (item.signStatus) {
					case 0:
						return 'status-pending';
					case 1:
						return 'status-signed';
					case 2:
						return 'status-expired';
					default:
						return '';
				}
			},

			// 显示提示消息
			showToast(message, type = 'info') {
				this.toastMessage = message;
				this.toastType = type;
				this.$refs.toast.show();
			}
		}
	};
</script>

<style scoped>
	/* 全局容器 */
	.page-container {
		min-height: 100vh;
		background-color: #F5F7FA;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	/* 导航栏 */
	.navbar-left {
		display: flex;
		align-items: center;
	}

	.back-button {
		display: flex;
		align-items: center;
	}

	.navbar-title {
		font-size: 18px;
		font-weight: 600;
		color: #4285f4;
		margin-left: 8px;
	}

	.navbar-right {
		display: flex;
		align-items: center;
	}

	.nav-item {
		padding: 4px;
		margin-left: 12px;
	}

	/* 搜索栏：修复宽度超出+搜索按钮遮挡问题 */
	.search-container {
		background-color: #FFFFFF;
		padding: 12px 0;
		border-bottom: 1px solid #EEEEEE;
	}

	/* 搜索栏容器添加左右内边距，限制内容宽度 */
	.search-container .container {
		padding: 0 16px;
		box-sizing: border-box;
	}

	.search-wrap {
		position: relative;
		width: 100%;
	}

	.search-input {
		width: 100%;
		height: 36px;
		border: 1px solid #EEEEEE;
		border-radius: 4px;
		padding: 0 12px;
		padding-right: 60px;
		/* 给搜索按钮预留足够显示空间 */
		font-size: 14px;
		box-sizing: border-box;
		/* 确保padding不撑大宽度 */
	}

	.search-icon {
		position: absolute;
		left: 12px;
		top: 50%;
		transform: translateY(-50%);
	}

	.search-btn {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		font-size: 14px;
		color: #333333;
		padding: 0 16px;
		white-space: nowrap;
		/* 禁止文字换行 */
	}

	/* 标签栏：修复宽度超出问题 */
	.tab-container {
		background-color: #F5F7FA;
		padding: 12px 0;
	}

	/* 标签栏容器添加左右内边距 */
	.tab-container .container {
		padding: 0 16px;
		box-sizing: border-box;
	}

	.tab-list {
		display: flex;
		gap: 8px;
		/* 用gap控制间距，比margin更均匀，避免溢出 */
		width: 100%;
	}

	.tab-item {
		flex: 1;
		/* 均匀分配宽度 */
		height: 32px;
		line-height: 32px;
		text-align: center;
		border: 1px solid #DDDDDD;
		border-radius: 16px;
		margin: 0;
		/* 移除原margin，改用gap控制间距 */
		background-color: #FFFFFF;
		color: #666666;
		font-size: 14px;
		box-sizing: border-box;
		/* 确保边框不撑大宽度 */
	}

	.tab-active {
		border-color: #4285F4;
		color: #4285F4;
	}

	/* 批量操作栏 */
	.batch-bar {
		background-color: #FFFFFF;
		border-bottom: 1px solid #EEEEEE;
		padding: 8px 0;
	}

	.batch-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 16px;
	}

	.batch-select {
		display: flex;
		align-items: center;
	}

	.batch-count {
		margin-left: 8px;
		font-size: 14px;
		color: #333333;
	}

	.batch-actions {
		display: flex;
	}

	.batch-btn {
		display: flex;
		align-items: center;
		margin-left: 16px;
		font-size: 14px;
	}

	.batch-btn text {
		margin-left: 4px;
	}

	/* 内容区 */
	.content-container {
		margin: 0 auto;
		padding: 16px;
	}

	.contract-list {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.contract-card {
		background-color: #FFFFFF;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.checkbox-container {
		width: 24px;
		height: 24px;
		border: 1px solid #DDDDDD;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.company-name {
		flex: 1;
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		margin: 0 12px;
	}

	.contract-status {
		padding: 2px 8px;
		border-radius: 12px;
		font-size: 12px;
	}

	.status-pending {
		background-color: #FFF2CC;
		color: #FF9900;
	}

	.status-signed {
		background-color: #D4EDDA;
		color: #28A745;
	}

	.status-expired {
		background-color: #F8D7DA;
		color: #DC3545;
	}

	.contract-info {
		font-size: 14px;
		color: #666666;
	}

	.info-row {
		display: flex;
		margin-bottom: 8px;
	}

	.info-label {
		color: #999999;
		min-width: 80px;
	}

	.info-value {
		color: #333333;
	}

	.red {
		color: #FF0000;
	}

	/* 操作按钮 */
	.action-buttons {
		display: flex;
		justify-content: flex-end;
		margin-top: 16px;
	}

	.action-btn {
		height: 32px;
		line-height: 32px;
		padding: 0 16px;
		border-radius: 4px;
		font-size: 14px;
		margin-left: 8px;
		display: flex;
		align-items: center;
	}

	.btn-icon {
		margin-right: 4px;
	}

	.preview,
	.download {
		background-color: #EEEEEE;
		color: #666666;
	}

	.sign {
		background-color: #28A745;
		color: #FFFFFF;
	}

	/* 无数据 */
	.no-data {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 48px 0;
	}

	.no-data-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		margin: 16px 0 8px;
	}

	.no-data-desc {
		font-size: 14px;
		color: #999999;
		text-align: center;
	}

	/* 新增按钮 */
	.add-btn {
		position: fixed;
		bottom: 24px;
		right: 24px;
		width: 56px;
		height: 56px;
		border-radius: 50%;
		background-color: #4285F4;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
	}

	/* 批量操作弹窗 */
	.batch-modal-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 16px 0;
	}

	.batch-count-info {
		margin-top: 16px;
		font-size: 14px;
		color: #666666;
	}
</style>